/**  
 * All rights Reserved, Designed By www.xiaozhanjiaoyu.cn
 * @Title:  WordSegmentationHandler.java   
 * @Package javaapplication.segmentation   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: knight.lu     
 * @date:   2018年11月22日 下午5:56:09   
 * @version V1.0 
 * @Copyright: 2018 www.xiaozhanjiaoyu.cn Inc. All rights reserved. 
 * 
 */
package com.ws.segmentation;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;
import com.component.AliAuthService;
import com.utils.HttpUtils;

/**   
 * @ClassName:  WordSegmentationHandler   
 * @Description: 分词处理
 * @author: knight.lu 
 * @date:   2018年11月22日 下午5:56:09   
 *     
 */
public class WordSegmentationHandler {
	

	private static final String METHOD = "POST";
	
	
	public List<WordResult> analysis(String requestText){
		   Map<String, String> headers = new HashMap<String, String>();
		    //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
		    headers.put("Authorization", "APPCODE " + AliAuthService.APP_CODE);
		    //根据API的要求，定义相对应的Content-Type
		    headers.put("Content-Type", "application/json; charset=UTF-8");
		    Map<String, String> querys = new HashMap<String, String>();
		    try {
		    	HttpResponse response = HttpUtils.doPost(AliAuthService.HOST, AliAuthService.PATH, METHOD, headers, querys, new Entity(50,requestText).parseJson());
		    	String responseContent = EntityUtils.toString(response.getEntity(), "UTF-8");
		    	JSONObject req1 = JSONObject.parseObject(responseContent);
		    	JSONObject req2 = req1.getJSONArray("outputs").getJSONObject(0).getJSONObject("outputValue");
		    	String value = req2.getString("dataValue");
		    	WordResultResponse wordResultResponse = JSONObject.parseObject(value, WordResultResponse.class);
		    	if(wordResultResponse !=null && 0 == wordResultResponse.getCode()) {
		    		return wordResultResponse.getTokens();
		    	}
		    } catch (Exception e) {
		    	e.printStackTrace();
		    }
		    return null;
	}
	
}
